package com.xiaoyu.tool.controller.client.wx;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 微信消息处理入口逻辑
 * Created by Administrator on 2017/5/11.
 */
@Slf4j
@RestController
@RequestMapping("/wx/portal")
public class WxProtroController {

    private final WxMpService wxMpService;

    private final WxMpMessageRouter wxMpMessageRouter;

    public WxProtroController(WxMpService wxMpService, WxMpMessageRouter wxMpMessageRouter) {
        this.wxMpService = wxMpService;
        this.wxMpMessageRouter = wxMpMessageRouter;
    }

    /**
     * 微信入口
     * */
    @GetMapping("/")
    public String get(@RequestParam(name = "signature", required = false) String signature,
                      @RequestParam(name = "timestamp", required = false) String timestamp,
                      @RequestParam(name = "nonce", required = false) String nonce,
                      @RequestParam(name = "echostr", required = false) String echostr) throws IOException {
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            log.error("token配置:报错:{}","请求参数非法，请核实!");
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            log.info("token配置成功:返回微信消息:{}",echostr);
            return echostr;
        }
        log.info("token配置非法请求");
        return "非法请求";
    }


    /**
     * 微信消息入口
     * */
    @PostMapping
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        // 明文传输的消息
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
        WxMpXmlOutMessage outMessage = route(inMessage);
        if (outMessage == null) {
            return "success";
        }
        return outMessage.toXml();
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.wxMpMessageRouter.route(message);
        } catch (Exception e) {
            log.error("消息规则代理失败:{}",e.getMessage());
        }
        return null;
    }

}
